<template>
    <a-drawer 
    v-model:visible="mVisible"
    :footer="!cFooter?null:undefined">
      <template #[key]="data" v-for="(item, key) in $slots">
        <slot :name="key" v-bind="data || {}"></slot>
      </template>
      <template #footer v-if="cFooter">
        <div class="m-dialog-footer">
        <slot name="appendBefore"></slot>
        <a-button v-bind="$attrs.cancelButtonProps || {}" v-if="showCancel !== false" @click="handleCancel">
          <slot name="cancelText">
            {{ $attrs.cancelText || '取消' }}
          </slot>
        </a-button>
        <slot name="appendCenter"></slot>
        <a-button v-bind="$attrs.okButtonProps || {}" v-if="showOk !== false" 
        :type="$attrs.okType	|| 'primary' " @click="handleOk">
          <slot name="okText">
            {{ $attrs.okText || '确定'}}
          </slot>
        </a-button>
        <slot name="appendAfter"></slot>
        </div>
      </template>
    </a-drawer>
</template>
<script setup lang="ts">
  import { computed, ref, useSlots, watch } from 'vue'
  const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    },
    showOk: {
      type: Boolean,
      default: true
    },
    showCancel: {
      type: Boolean,
      default: true
    }
  })
  const emits = defineEmits(['update:visible','afterClose','ok','cancel'])
  const mVisible = ref(props.visible)
  watch(()=>props.visible,()=>{
    mVisible.value = props.visible
  })
  watch(()=>mVisible.value,()=>{
    emits('update:visible', mVisible.value)
    if(mVisible.value == false) {
      emits('afterClose')
    }
  })
  const slots = useSlots();
  const cFooter = computed<Boolean>(()=>{
    if(props.showOk !== false) {
      return true;
    }
    if(props.showCancel !== false) {
      return true;
    }
    if(Object.keys(slots).includes('appendBefore')) {
      return true;
    }
    if(Object.keys(slots).includes('appendCenter')) {
      return true;
    }
    if(Object.keys(slots).includes('appendAfter')) {
      return true;
    }
    return false;
})
const handleCancel = () =>{
  mVisible.value = false;
  emits('update:visible', false)
  emits('cancel')
}
const handleOk = () =>{
  emits('ok')
}
defineExpose({
  openDrawer() {
    mVisible.value = true;
  },
  closeDrawer() {
    handleCancel()
  },
})
</script>
<style lang="less" scoped>
.m-dialog-footer {
  display: flex;
  justify-content: end;
  gap: 8px;
}
</style>